﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Rapor;
using ConfExpert.Utility;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using DevTeam;

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class TopBolmeDepo : XForm
    {
        public TopBolmeDepo()
        {
            InitializeComponent();
        }

        BindingSource bs1, bs2;
        private void TopBolmeDepo_Load(object sender, EventArgs e)
        {
            //3 gridi birbirine bağlama
            //Sadece ilki init, diğerleri addDetailGrid fonksiyonlarını kullanıyor.
            //Virgüller ayrılmış PK lar destekleniyor.

            bs1 = gv1.Init("GetTopBol", chkShowAll.Checked);
            bs2 = gv1.AddDetailGrid(gv2, "Roll1Id");

            
            //Grid e expression içeren sütun ekleme ;
            //{FK} geçen yere fonksiyon otomatik olarak ilk FK nın ismini yazıyor.            
            //gvCELines2.SutunEkle("SelectedQty", typeof(int), "Iif(ISNULL(KesilecekMiktar,0)=0, Qty,ISNULL(KesilecekMiktar,0))");

            gv2.AddColumn("Qty2x", typeof(decimal), "Iif(Done = 1, 0, Qty2)");
            gv2.AddColumn("sel", typeof(int), "0");            

            gv1.AddColumn("Qty2", typeof(decimal), "SUM(Child({FK}).Qty2x)");
            gv1.AddColumn("OrgQty", typeof(decimal), "ISNULL(Qty1,0)+ISNULL(Qty2,0)");
            gv1.AddColumn("Adet", typeof(int), "COUNT(Child({FK}).Roll2Id)");
            gv1.AddColumn("sel", typeof(int), "MAX(Child({FK}).sel)");
            gv1.AddColumn("CE", typeof(string), "Iif(MAX(Child({FK}).CikisEmriId)>0,'*','')");

            gv1.MakeReadOnly();
            gv2.MakeReadOnly();

            //GridManager gm = GridManager.GetManager(gv1);
            //gm.GridMenu.AddMenu("Top Bölme Emri Yazdır", DokumAl);
            //gm.GridMenu.AddMenu("Etiket Yazdır", EtiketBas);
            //gm.GridMenu.AddMenu("Bölündü Olarak İşaretle", Bolundu);

            //gv1.OptionsView.EnableAppearanceEvenRow = false;
            //gv1.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gv_RowStyle);
            gv1.RowCellStyle += new RowCellStyleEventHandler(gv_RowCellStyle);

            //Devx MakeColumnVisible eklemiş, invisible ını da ben ekledim :)
            gv2.MakeColumnInvisible("BolunenTopId", "Roll1Id", "Qty2x", "sel", "CikisEmri0Id");
            gv1.MakeColumnInvisible("Qty1", "Qty2", "sel","ProductId", "IsTela");

            gv1.FormatAsNumber(1, "OrgQty");
            gv2.FormatAsNumber(1, "Qty2");

            //Toplam sütunu ekleme
            gv2.AddSummary("Qty2");
            gv1.AddSummary("Adet");

            btnGuncelle.ItemClick += BtnGuncelle_ItemClick;
            chkShowAll.CheckedChanged += ChkShowAll_CheckedChanged;
            teCEId.EditValueChanged += TeCEId_EditValueChanged;
            teTopId.EditValueChanged += TeTopId_EditValueChanged;
            txtInfo.Caption = "Top Bölme Talepleri";

            teCEId.Visibility = ytk(177) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;

            bs1.CurrentChanged += new EventHandler(bs1_CurrentChanged);
            gv1.BestFitColumns();
            gv2.BestFitColumns();

            btnBolunenKucukParcalar.ItemClick += BtnBolunenKucukParcalar_ItemClick;

        }

        private void BtnBolunenKucukParcalar_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AppSession.MainForm.ShowMdiChildForm(typeof(BolunenKucukParca));
            btnGuncelle.PerformClick();

            //using (BolunenKucukParca bp = new BolunenKucukParca())
            //    bp.ShowDialog();
        }

        void bs1_CurrentChanged(object sender, EventArgs e)
        {
            txtInfo.Caption = intParse(bs1, "Roll1Id").ToString() + ". " + gv1.GetFocusedRowCellDisplayText("Name").ToString();
        }

        bool seri = false;
        private void TeTopId_EditValueChanged(object sender, EventArgs e)
        {
            if (!seri)
            {
                seri = true;
                bs1.Filter = bs2.Filter = string.Empty;
                teCEId.EditValue = string.Empty;

                if (teTopId.EditValue.ToInt() > 0)
                {
                    int TopId = teTopId.EditValue.ToInt();
                    string expression = "Iif(Roll1Id = " + TopId.ToString() + " OR Roll2Id = " + TopId.ToString() + ", 1, 0)";
                    gv2.ChangeExpression("sel", expression);
                    bs1.Filter = bs2.Filter = "sel > 0";
                    gv1.BestFitColumns();
                    gv2.BestFitColumns();
                }
                seri = false;
            }
        }

        private void TeCEId_EditValueChanged(object sender, EventArgs e)
        {
            if (!seri)
            {
                seri = true;
                bs1.Filter = bs2.Filter = string.Empty;
                teTopId.EditValue = string.Empty;

                if (teCEId.EditValue.ToInt() > 0)
                {
                    int cikisEmriId = teCEId.EditValue.ToInt();
                    string expression = "Iif(CikisEmriId = " + cikisEmriId.ToString() + " OR CikisEmri0Id = " + cikisEmriId.ToString() + ", 1, 0)";
                    gv2.ChangeExpression("sel", expression);
                    bs1.Filter = bs2.Filter = "sel > 0";
                    gv1.BestFitColumns();
                    gv2.BestFitColumns();
                }
                seri = false;
            }
        }

        void gv_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName.Contains("Qty"))
                e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
        }

        void gv_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.RowHandle > -1)
            {
                if (e.RowHandle == gv1.FocusedRowHandle)
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);
            }
        }
        
        void gv1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (intParse(bs1, "ProductId") > 0)
                txtInfo.Caption = AppSession.Lookups.V_Kumas.FindByProductId(intParse(bs1, "ProductId")).Name;
            else
                txtInfo.Caption = string.Empty;
        }


        void gv1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //if (gv.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            e.Cancel = true;    // !(gv2.FocusedColumn.FieldName.Contains("Qty2") || gv2.FocusedColumn.FieldName == "Done");

        }

        private void BtnGuncelle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ds.Clear();

            gv1.RefreshDataSource("GetTopBol", chkShowAll.Checked);
            gv1.BestFitColumns();
        }

        string GetBolunenTopIds()
        {
            if (gv1.SelectedRowsCount < 1)
                gv1.SelectRow(gv1.FocusedRowHandle);

            List<string> rolls = new List<string>();
            TelaIds.Clear();
            KumasIds.Clear();

            foreach (int handle in gv1.GetSelectedRows())
            {
                string rollId = gv1.GetRowCellValue(handle, "Roll1Id").ToString();

                //foreach (DataRow dr in gv1.Dataset().Tables[1].Select("sel = 1 AND Roll1Id=" + rollId, string.Empty))
                foreach (DataRow dr in gv1.Dataset().Tables[1].Select("Roll1Id=" + rollId, string.Empty))
                {
                    string btid = dr["BolunenTopId"].ToString();
                    rolls.Add(btid);

                    if ((bool)gv1.GetDataRow(handle)["IsTela"])
                        TelaIds.Add(btid);
                    else
                        KumasIds.Add(btid);
                }
            }

            return String.Join(",", rolls.ToArray());
        }

        List<string> KumasIds = new List<string>();
        List<string> TelaIds = new List<string>();
        private string GetKumasRolls()
        {
            return String.Join(",", KumasIds.ToArray());
        }

        private string GetTelaRolls()
        {
            return String.Join(",", TelaIds.ToArray());
        }

        void Bolundu(object sender, EventArgs e)
        {
            if (teCEId.EditValue.ToStr().Trim() == string.Empty && teTopId.EditValue.ToStr().Trim() == string.Empty)
            {
                ShowErrorMessage("ÇıkışEmriId veya TopId üzerinden filtreleme gerekiyor !");
                return;
            }
            Session.DataManager.ExecuteNonQuery("UpdTopBolYeni", GetBolunenTopIds(), WhoAmI);
            
            btnGuncelle.PerformClick();
        }

        void EtiketBas(object sender, EventArgs e)
        {
            if (teCEId.EditValue.ToStr().Trim() == string.Empty && teTopId.EditValue.ToStr().Trim() == string.Empty)
            {
                ShowErrorMessage("ÇıkışEmriId veya TopId üzerinden filtreleme gerekiyor !");
                return;
            }
            GetBolunenTopIds();

            if (KumasIds.Count > 0)
            {
                TopEtiketleri2 barcode = new TopEtiketleri2(Enums.EtiketTipi.TopBol, GetKumasRolls());
                barcode.ShowDialog();
            }

            if (TelaIds.Count > 0)
            {
                Rapor.TelaBarkod telaBarcode = new Rapor.TelaBarkod(Enums.EtiketTipi.TopBol, GetTelaRolls());
                telaBarcode.ShowPreview();
            }
        }

        void DokumAl(object sender, EventArgs e)
        {
            //if (teCEId.Text.Trim() == string.Empty && teTopId.Text.Trim() == string.Empty)
            //{
            //    ShowErrorMessage("ÇıkışEmriId veya TopId üzerinden filtreleme gerekiyor !");
            //    return;
            //}
            Rapor.xrTopKesim k = new Rapor.xrTopKesim(GetBolunenTopIds());
            k.ShowPreview();
        }

        private void ChkShowAll_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            btnGuncelle.PerformClick();
        }
    }
}
